/*
 * bill.c
 *
 *  Created on: Apr 20, 2011
 *      Author: Gilad & Yotam
 */

#include <stdlib.h>
#include "bill.h"
#include "car.h"
#include "commontools.h"
#include <string.h>
#include <assert.h>

struct BillElement_t {
	char* carName;
	int carLicense;
	int kmDrove;
	int pricePerKm;
	bool sale;
	int price;
};

void* copyBillElement(void* element) {
	if (element == NULL) {
		return NULL;
	}
	BillElement newBillElement = malloc(sizeof(struct BillElement_t));
	if (newBillElement == NULL) {
		return NULL;
	}
	BillElement billElement = ((BillElement) element);

	newBillElement->carName = copyName(billElement->carName);
	if (newBillElement->carName == NULL) {
		free(newBillElement);
		return NULL;
	}
	newBillElement->carLicense = billElement->carLicense;
	newBillElement->kmDrove = billElement->kmDrove;
	newBillElement->pricePerKm = billElement->pricePerKm;
	newBillElement->sale = billElement->sale;
	newBillElement->price = billElement->price;

	return newBillElement;
}

void freeBillElement(void* element) {
	if (element == NULL) {
		return;
	}
	BillElement billElement = (BillElement) element;
	free(billElement->carName);
	free(billElement);
}

BillElement billCreateNewElement(Car car, int kmDrove) {
	if (car == NULL) {
		return NULL;
	}
	BillElement newBillElement = malloc(sizeof(struct BillElement_t));
	if (newBillElement == NULL) {
		return NULL;
	}

	newBillElement->carName = copyName(carGetName(car));
	if (newBillElement->carName == NULL) {
		free(newBillElement);
		return NULL;
	}
	newBillElement->carLicense = carGetLicensePlate(car);
	newBillElement->kmDrove = kmDrove;
	newBillElement->pricePerKm = carGetPrice(car);

	if ((carGetSaleStatus(car)) && (kmDrove >= carGetSaleKmMin(car))
			&& (kmDrove <= carGetSaleKmMax(car))) {
		newBillElement->sale = true;
		newBillElement->price = carGetSalePrice(car);
	} else {
		newBillElement->sale = false;
		newBillElement->price = kmDrove * newBillElement->pricePerKm;
	}
	return newBillElement;
}

int billGetCarLicense(BillElement billElement) {
	assert(billElement);
	return billElement->carLicense;
}

char* billGetCarName(BillElement billElement) {
	assert(billElement);
	return billElement->carName;
}

int billGetKmDrove(BillElement billElement) {
	assert(billElement);
	return billElement->kmDrove;
}

int billGetPricePerKm(BillElement billElement) {
	assert(billElement);
	return billElement->pricePerKm;
}

bool billGetCarSaleStatus(BillElement billElement) {
	assert(billElement);
	return billElement->sale;
}

int billGetPrice(BillElement billElement) {
	assert(billElement);
	return billElement->price;
}
